package com.home.qh.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.home.qh.dao.PartnerDao;
import com.home.qh.model.Partner;


/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> 
 */
@Repository
public class PartnerDaoHibernate extends GenericDaoHibernate<Partner, Long> implements PartnerDao {

    /**
     * Constructor to create a Generics-based version using Partner as the entity
     */
    public PartnerDaoHibernate() {
        super(Partner.class);
    }

    /**
     * {@inheritDoc}
     */
    public List<Partner> getPartnerByCodeAndName(String partnerCode, String partnerName){
    	List<Partner> cities = getHibernateTemplate().find("from Partner where name like '%?%'", partnerName);
        if (cities.isEmpty()) {
            return null;
        } else {
            return cities;
        }
    }
    
    public List<Partner> getPartnerByPartner(Partner partner, String sort, boolean desc, int startResult, int maxResults) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Partner.class);

        if (partner.getCode() != null) {
        	criteria.add(Restrictions.or(Restrictions.eq("code", partner.getCode()), Restrictions.eq("name", partner.getName())));
		}
        
        if (partner.getCity() != null) {        	
        	criteria.add(Restrictions.eq("city.id", partner.getCity().getId()));
		}

        if(sort != null && !"".equalsIgnoreCase(sort)) {
            if(desc) criteria.addOrder(Order.desc(sort));
            else criteria.addOrder(Order.asc(sort));
        }

        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        
        return getHibernateTemplate().findByCriteria(criteria, startResult, maxResults);
	}

   
}
